using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Windows.Forms;
using WIT.DAQ.Core.Forms;
using WIT.DAQ.Core.Helper;

namespace WIT.DAQ.Core;

/// <summary>
/// WIT.DAQ.Core入口
/// </summary>
public class Entrance
{
	/// <summary>
	/// 启动主程序
	/// </summary>
	/// <param name="clientName">客户端名称</param>
	/// <param name="customMenu">自定义菜单</param>
	public static void Launch(string clientName = null, CustomMenu customMenu = null)
	{
		string processName = Process.GetCurrentProcess().ProcessName;
		Process[] processesByName = Process.GetProcessesByName(processName);
		if (processesByName.Length == 1)
		{
			ThreadExceptionHandler @object = new ThreadExceptionHandler();
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
			Application.ThreadException += @object.UIThreadException;
			AppDomain.CurrentDomain.UnhandledException += @object.CurrentDomain_UnhandledException;
			AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(defaultValue: false);
			if (clientName == null)
			{
				Application.Run(new MainForm(processName, customMenu));
			}
			else
			{
				Application.Run(new MainForm(clientName, customMenu));
			}
		}
		else
		{
			string text = clientName ?? processName;
			MessageBox.Show(text + " 已运行");
		}
	}

	private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
	{
		string name = new AssemblyName(args.Name).Name;
		if (name.EndsWith(".resources"))
		{
			return null;
		}
		string @namespace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
		string name2 = name.Replace(".", "_");
		ResourceManager resourceManager = new ResourceManager(@namespace + ".Properties.Resources", Assembly.GetExecutingAssembly());
		byte[] array = (byte[])resourceManager.GetObject(name2);
		if (array == null)
		{
			string name3 = @namespace + ".Libs." + name + ".dll";
			using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name3);
			array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
		}
		return Assembly.Load(array);
	}
}
